package com.lu.interceptor;

import com.alibaba.fastjson2.JSON;
import com.lu.common.utils.JwtUtil;
import com.lu.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtValidateInterceptor implements HandlerInterceptor {//jwt拦截器

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求里拿到token
        String  token = request.getHeader("X-Token");
        log.debug(request.getRequestURI() + "需要验证:" + token);
        if (token!=null){
            try {
                jwtUtil.parseToken(token);
                //如果能到这里就一定成功
                //打印日志
                log.debug(request.getRequestURI() + "验证通过");
                return true;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        log.debug(request.getRequestURI() + "验证失败，禁止访问");
        //因为是前后端分离，所以需要返回给前端一个信息，以json形式
        response.setContentType("application/json;charset=utf-8");
        Result<Object> fail = Result.fail(20003, "jwt无效，请重新登录");
        response.getWriter().write(JSON.toJSONString(fail));
        return false;//拦截
    }
}
